﻿using Newtonsoft.Json;

namespace Futuret.Core.Extensions;

/// <summary>
///     Author: Riva
///     Date: 2023/7/11 21:47
///     Description: Json字符串扩展类
/// </summary>
public static class JsonExtension
{
    /// <summary>
    ///     Object转Json
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="ignoreDefault"></param>
    /// <returns></returns>
    public static string ToJson(this object obj, bool ignoreDefault = false)
    {
        return JsonConvert.SerializeObject(obj, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            DefaultValueHandling = ignoreDefault ? DefaultValueHandling.Ignore : DefaultValueHandling.Include
        });
    }
    
    /// <summary>
    ///     String转Object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T? ToObject<T>(this string json)
    {
        if (typeof(T).Name.Equals("string", StringComparison.OrdinalIgnoreCase))
            return (T)Convert.ChangeType(json, typeof(T));
        return JsonConvert.DeserializeObject<T>(json);
    }
}